﻿
//need
Ext.define('Ext.data.Connection', {
    mixins: {
        observable: 'Ext.mixin.Observable'
    },

    requires: [
        'Ext.data.flash.BinaryXhr'
    ],

    statics: {
        requestId: 0
    },

    config: {

        url: null,


        async: true,


        username: '',


        password: '',


        disableCaching: true,


        withCredentials: false,


        binary: false,


        cors: false,

        isXdr: false,

        defaultXdrContentType: 'text/plain',


        disableCachingParam: '_dc',


        timeout: 30000,


        extraParams: null,


        autoAbort: false,


        method: null,


        defaultHeaders: null,


        defaultPostHeader: 'application/x-www-form-urlencoded; charset=UTF-8',


        useDefaultXhrHeader: true,


        defaultXhrHeader: 'XMLHttpRequest'
    },

    constructor: function (config) {

        this.mixins.observable.constructor.call(this, config);




        this.requests = {};
    },


    request: function (options) {
        options = options || {};
        var me = this,
            scope = options.scope || window,
            username = options.username || me.getUsername(),
            password = options.password || me.getPassword() || '',
            async,
            requestOptions,
            request,
            headers,
            xdr,
            xhr;

        if (me.fireEvent('beforerequest', me, options) !== false) {

            requestOptions = me.setOptions(options, scope);

            if (me.isFormUpload(options)) {
                me.upload(options.form, requestOptions.url, requestOptions.data, options);
                return null;
            }


            if (options.autoAbort || me.getAutoAbort()) {
                me.abort();
            }


            async = options.async !== false ? (options.async || me.getAsync()) : false;
            xhr = me.openRequest(options, requestOptions, async, username, password);


            xdr = me.getIsXdr();
            if (!xdr) {
                headers = me.setupHeaders(xhr, options, requestOptions.data, requestOptions.params);
            }


            request = {
                id: ++Ext.data.Connection.requestId,
                xhr: xhr,
                headers: headers,
                options: options,
                async: async,
                binary: options.binary || me.getBinary(),
                timeout: setTimeout(function () {
                    request.timedout = true;
                    me.abort(request);
                }, options.timeout || me.getTimeout())
            };

            me.requests[request.id] = request;
            me.latestId = request.id;

            if (async) {
                if (!xdr) {
                    xhr.onreadystatechange = Ext.Function.bind(me.onStateChange, me, [request]);
                }
            }

            if (xdr) {
                me.processXdrRequest(request, xhr);
            }


            xhr.send(requestOptions.data);
            if (!async) {
                return me.onComplete(request);
            }
            return request;
        } else {
            Ext.callback(options.callback, options.scope, [options, undefined, undefined]);
            return null;
        }
    },

    processXdrRequest: function (request, xhr) {
        var me = this;


        delete request.headers;

        request.contentType = request.options.contentType || me.getDefaultXdrContentType();

        xhr.onload = Ext.Function.bind(me.onStateChange, me, [request, true]);
        xhr.onerror = xhr.ontimeout = Ext.Function.bind(me.onStateChange, me, [request, false]);
    },

    processXdrResponse: function (response, xhr) {

        response.getAllResponseHeaders = function () {
            return [];
        };
        response.getResponseHeader = function () {
            return '';
        };
        response.contentType = xhr.contentType || this.getDefaultXdrContentType();
    },


    upload: function (form, url, params, options) {
        form = Ext.getDom(form);
        options = options || {};

        var id = Ext.id(),
            frame = document.createElement('iframe'),
            hiddens = [],
            encoding = 'multipart/form-data',
            buf = {
                target: form.target,
                method: form.method,
                encoding: form.encoding,
                enctype: form.enctype,
                action: form.action
            },
            addField = function (name, value) {
                hiddenItem = document.createElement('input');
                Ext.fly(hiddenItem).set({
                    type: 'hidden',
                    value: value,
                    name: name
                });
                form.appendChild(hiddenItem);
                hiddens.push(hiddenItem);
            },
            hiddenItem, obj, value, name, vLen, v, hLen, h;


        Ext.fly(frame).set({
            id: id,
            name: id,
            cls: Ext.baseCSSPrefix + 'hidden-display',
            src: Ext.SSL_SECURE_URL
        });

        document.body.appendChild(frame);


        if (document.frames) {
            document.frames[id].name = id;
        }

        Ext.fly(form).set({
            target: id,
            method: 'POST',
            enctype: encoding,
            encoding: encoding,
            action: url || buf.action
        });


        if (params) {
            obj = Ext.Object.fromQueryString(params) || {};

            for (name in obj) {
                if (obj.hasOwnProperty(name)) {
                    value = obj[name];
                    if (Ext.isArray(value)) {
                        vLen = value.length;
                        for (v = 0; v < vLen; v++) {
                            addField(name, value[v]);
                        }
                    } else {
                        addField(name, value);
                    }
                }
            }
        }


        Ext.get(frame).on({
            load: Ext.Function.bind(this.onUploadComplete, this, [frame, options]),
            single: !Ext.isOpera
        });

        form.submit();


        Ext.fly(form).set(buf);

        for (hLen = hiddens.length, h = 0; h < hLen; h++) {
            Ext.removeNode(hiddens[h]);
        }
    },


    onUploadComplete: function (frame, options) {
        var me = this,

            response = {
                responseText: '',
                responseXML: null
            }, callback, success, doc, contentNode;

        try {
            doc = (frame && (frame.contentWindow.document || frame.contentDocument)) || (window.frames[frame.id] || {}).document;


            if (doc) {

                if (Ext.isOpera && doc.location == Ext.SSL_SECURE_URL) {
                    return;
                }

                if (doc.body) {



                    if ((contentNode = doc.body.firstChild) && /pre/i.test(contentNode.tagName)) {
                        response.responseText = contentNode.textContent || contentNode.innerText;
                    }



                    else if ((contentNode = doc.getElementsByTagName('textarea')[0])) {
                        response.responseText = contentNode.value;
                    }

                    else {
                        response.responseText = doc.body.textContent || doc.body.innerText;
                    }
                }


                response.responseXML = doc.XMLDocument || doc;
                callback = options.success;
                success = true;

            } else {
                Ext.Error.raise("Could not acquire a suitable connection for the file upload service.");
            }
        } catch (e) {

            response.responseText = '{success:false,message:"' + Ext.String.trim(e.message || e.description) + '"}';
            callback = options.failure;
            success = false;
        }

        me.fireEvent(success ? 'requestcomplete' : 'requestexception', me, response, options);

        Ext.callback(callback, options.scope, [response, options]);
        Ext.callback(options.callback, options.scope, [options, success, response]);


        Ext.defer(Ext.removeNode, 100, Ext, [frame]);

    },


    isFormUpload: function (options) {
        var form = this.getForm(options);
        if (form) {
            return (options.isUpload || (/multipart\/form-data/i).test(form.getAttribute('enctype')));
        }
        return false;
    },


    getForm: function (options) {
        var form = options.form || null;
        if (form) {
            form = Ext.getDom(form);
        }
        return form;
    },


    setOptions: function (options, scope) {
        var me = this,
            params = options.params || {},
            extraParams = me.getExtraParams(),
            urlParams = options.urlParams,
            url = options.url || me.getUrl(),
            jsonData = options.jsonData,
            method,
            disableCache,
            data;



        if (Ext.isFunction(params)) {
            params = params.call(scope, options);
        }


        if (Ext.isFunction(url)) {
            url = url.call(scope, options);
        }

        url = this.setupUrl(options, url);

        if (!url) {
            Ext.Error.raise({
                options: options,
                msg: 'No URL specified'
            });
        }


        data = options.rawData || options.binaryData || options.xmlData || jsonData || null;
        if (jsonData && !Ext.isPrimitive(jsonData)) {
            data = Ext.encode(data);
        }

        if (options.binaryData) {
            if (!Ext.isArray(options.binaryData)) {
                Ext.log.warn("Binary submission data must be an array of byte values! Instead got " + typeof (options.binaryData));
            }
            if (me.nativeBinaryPostSupport()) {
                data = (new Uint8Array(options.binaryData));
                if ((Ext.isChrome && Ext.chromeVersion < 22) || Ext.isSafari || Ext.isGecko) {
                    data = data.buffer;
                }
            }
        }


        if (Ext.isObject(params)) {
            params = Ext.Object.toQueryString(params);
        }

        if (Ext.isObject(extraParams)) {
            extraParams = Ext.Object.toQueryString(extraParams);
        }

        params = params + ((extraParams) ? ((params) ? '&' : '') + extraParams : '');

        urlParams = Ext.isObject(urlParams) ? Ext.Object.toQueryString(urlParams) : urlParams;

        params = this.setupParams(options, params);


        method = (options.method || me.getMethod() || ((params || data) ? 'POST' : 'GET')).toUpperCase();
        this.setupMethod(options, method);


        disableCache = options.disableCaching !== false ? (options.disableCaching || me.getDisableCaching()) : false;

        if (method === 'GET' && disableCache) {
            url = Ext.urlAppend(url, (options.disableCachingParam || me.getDisableCachingParam()) + '=' + (new Date().getTime()));
        }


        if ((method == 'GET' || data) && params) {
            url = Ext.urlAppend(url, params);
            params = null;
        }


        if (urlParams) {
            url = Ext.urlAppend(url, urlParams);
        }

        return {
            url: url,
            method: method,
            data: data || params || null
        };
    },


    setupUrl: function (options, url) {
        var form = this.getForm(options);
        if (form) {
            url = url || form.action;
        }
        return url;
    },



    setupParams: function (options, params) {
        var form = this.getForm(options),
            serializedForm;
        if (form && !this.isFormUpload(options)) {
            serializedForm = Ext.Element.serializeForm(form);
            params = params ? (params + '&' + serializedForm) : serializedForm;
        }
        return params;
    },


    setupMethod: function (options, method) {
        if (this.isFormUpload(options)) {
            return 'POST';
        }
        return method;
    },


    setupHeaders: function (xhr, options, data, params) {
        var me = this,
            headers = Ext.apply({}, options.headers || {}, me.getDefaultHeaders() || {}),
            contentType = me.getDefaultPostHeader(),
            jsonData = options.jsonData,
            xmlData = options.xmlData,
            type = 'Content-Type',
            key,
            header;

        if (!headers.hasOwnProperty(type) && (data || params)) {
            if (data) {
                if (options.rawData) {
                    contentType = 'text/plain';
                } else {
                    if (xmlData && Ext.isDefined(xmlData)) {
                        contentType = 'text/xml';
                    } else if (jsonData && Ext.isDefined(jsonData)) {
                        contentType = 'application/json';
                    }
                }
            }
            headers[type] = contentType;
        }

        if (me.getUseDefaultXhrHeader() && !headers['X-Requested-With']) {
            headers['X-Requested-With'] = me.getDefaultXhrHeader();
        }



        if (headers[type] === undefined || headers[type] === null) {
            delete headers[type];
        }


        try {
            for (key in headers) {
                if (headers.hasOwnProperty(key)) {
                    header = headers[key];
                    xhr.setRequestHeader(key, header);
                }
            }
        } catch (e) {
            me.fireEvent('exception', key, header);
        }
        return headers;
    },


    newRequest: function (options) {
        var me = this,
            xhr;

        if (options.binaryData) {

            if (me.nativeBinaryPostSupport()) {
                xhr = me.getXhrInstance();
            } else {

                xhr = new Ext.data.flash.BinaryXhr();
            }
        } else if ((options.cors || me.getCors()) && Ext.isIE && Ext.ieVersion <= 9) {
            xhr = me.getXdrInstance();
            me.setIsXdr(true);
        } else {
            xhr = me.getXhrInstance();
        }

        return xhr;
    },


    openRequest: function (options, requestOptions, async, username, password) {
        var me = this,
            xhr = me.newRequest(options);

        if (username) {
            xhr.open(requestOptions.method, requestOptions.url, async, username, password);
        } else {
            if (me.getIsXdr()) {
                xhr.open(requestOptions.method, requestOptions.url);
            } else {
                xhr.open(requestOptions.method, requestOptions.url, async);
            }
        }

        if (options.binary || me.getBinary()) {
            if (window.Uint8Array) {
                xhr.responseType = 'arraybuffer';
            } else if (xhr.overrideMimeType) {




                xhr.overrideMimeType('text\/plain; charset=x-user-defined');
            } else if (!Ext.isIE) {
                Ext.log.warn("Your browser does not support loading binary data using Ajax.");
            }
        }

        if (options.withCredentials || me.getWithCredentials()) {
            xhr.withCredentials = true;
        }

        return xhr;
    },


    getXdrInstance: function () {
        var xdr;

        if (Ext.ieVersion >= 8) {
            xdr = new XDomainRequest();
        } else {
            Ext.Error.raise({
                msg: 'Your browser does not support CORS'
            });
        }

        return xdr;
    },


    getXhrInstance: (function () {
        var options = [function () {
            return new XMLHttpRequest();
        }, function () {
            return new ActiveXObject('MSXML2.XMLHTTP.3.0');
        }, function () {
            return new ActiveXObject('MSXML2.XMLHTTP');
        }, function () {
            return new ActiveXObject('Microsoft.XMLHTTP');
        }], i = 0,
            len = options.length,
            xhr;

        for (; i < len; ++i) {
            try {
                xhr = options[i];
                xhr();
                break;
            } catch (e) {
            }
        }
        return xhr;
    }()),


    isLoading: function (request) {
        if (!request) {
            request = this.getLatest();
        }
        if (!(request && request.xhr)) {
            return false;
        }

        var state = request.xhr.readyState,
            Cls = Ext.data.flash && Ext.data.flash.BinaryXhr;

        return ((request.xhr instanceof Cls) && state != 4) || !(state === 0 || state == 4);
    },


    abort: function (request) {
        var me = this,
            xhr;

        if (!request) {
            request = me.getLatest();
        }

        if (request && me.isLoading(request)) {

            xhr = request.xhr;
            try {
                xhr.onreadystatechange = null;
            } catch (e) {


                xhr.onreadystatechange = Ext.emptyFn;
            }
            xhr.abort();
            me.clearTimeout(request);
            if (!request.timedout) {
                request.aborted = true;
            }
            me.onComplete(request);
            me.cleanup(request);
        }
    },


    abortAll: function () {
        var requests = this.requests,
            id;

        for (id in requests) {
            if (requests.hasOwnProperty(id)) {
                this.abort(requests[id]);
            }
        }
    },


    getLatest: function () {
        var id = this.latestId,
            request;

        if (id) {
            request = this.requests[id];
        }
        return request || null;
    },


    onStateChange: function (request, xdrResult) {
        var me = this,
            globalEvents = Ext.GlobalEvents;


        if ((request.xhr && request.xhr.readyState == 4) || me.isXdr) {
            me.clearTimeout(request);
            me.onComplete(request, xdrResult);
            me.cleanup(request);
            if (globalEvents.hasListeners.idle) {
                globalEvents.fireEvent('idle');
            }
        }
    },


    clearTimeout: function (request) {
        clearTimeout(request.timeout);
        delete request.timeout;
    },


    cleanup: function (request) {
        request.xhr = null;
        delete request.xhr;
    },


    onComplete: function (request, xdrResult) {
        var me = this,
            options = request.options,
            xhr,
            result,
            success,
            response;

        try {
            xhr = request.xhr;
            result = me.parseStatus(xhr.status);
            if (result.success) {



                result.success = xhr.readyState === 4;
            }
        } catch (e) {

            result = {
                success: false,
                isException: false
            };

        }
        success = me.isXdr ? xdrResult : result.success;

        if (success) {
            response = me.createResponse(request);
            me.fireEvent('requestcomplete', me, response, options);
            Ext.callback(options.success, options.scope, [response, options]);
        } else {
            if (result.isException || request.aborted || request.timedout) {
                response = me.createException(request);
            } else {
                response = me.createResponse(request);
            }
            me.fireEvent('requestexception', me, response, options);
            Ext.callback(options.failure, options.scope, [response, options]);
        }
        Ext.callback(options.callback, options.scope, [options, success, response]);
        delete me.requests[request.id];
        return response;
    },


    parseStatus: function (status) {

        status = status == 1223 ? 204 : status;

        var success = (status >= 200 && status < 300) || status == 304,
            isException = false;

        if (!success) {
            switch (status) {
                case 12002:
                case 12029:
                case 12030:
                case 12031:
                case 12152:
                case 13030:
                    isException = true;
                    break;
            }
        }
        return {
            success: success,
            isException: isException
        };
    },


    createResponse: function (request) {
        var me = this,
            xhr = request.xhr,
            isXdr = me.getIsXdr(),
            headers = {},
            lines = isXdr ? [] : xhr.getAllResponseHeaders().replace(/\r\n/g, '\n').split('\n'),
            count = lines.length,
            line, index, key, response, byteArray;

        while (count--) {
            line = lines[count];
            index = line.indexOf(':');
            if (index >= 0) {
                key = line.substr(0, index).toLowerCase();
                if (line.charAt(index + 1) == ' ') {
                    ++index;
                }
                headers[key] = line.substr(index + 1);
            }
        }

        request.xhr = null;
        delete request.xhr;

        response = {
            request: request,
            requestId: request.id,
            status: xhr.status,
            statusText: xhr.statusText,
            getResponseHeader: function (header) {
                return headers[header.toLowerCase()];
            },
            getAllResponseHeaders: function () {
                return headers;
            }
        };

        if (isXdr) {
            me.processXdrResponse(response, xhr);
        }

        if (request.binary) {
            response.responseBytes = me.getByteArray(xhr);
        } else {




            response.responseText = xhr.responseText;
            response.responseXML = xhr.responseXML;
        }



        xhr = null;
        return response;
    },


    createException: function (request) {
        return {
            request: request,
            requestId: request.id,
            status: request.aborted ? -1 : 0,
            statusText: request.aborted ? 'transaction aborted' : 'communication failure',
            aborted: request.aborted,
            timedout: request.timedout
        };
    },


    getByteArray: function (xhr) {
        var response = xhr.response,
            responseBody = xhr.responseBody,
            Cls = Ext.data.flash && Ext.data.flash.BinaryXhr,
            byteArray, responseText, len, i;

        if (xhr instanceof Cls) {

            byteArray = xhr.responseBytes;
        } else if (window.Uint8Array) {



            byteArray = response ? new Uint8Array(response) : [];
        } else if (Ext.isIE9p) {




            try {
                byteArray = new VBArray(responseBody).toArray();
            } catch (e) {




                byteArray = [];
            }
        } else if (Ext.isIE) {





            if (!this.self.vbScriptInjected) {
                this.injectVBScript();
            }
            getIEByteArray(xhr.responseBody, byteArray = []);
        } else {


            byteArray = [];
            responseText = xhr.responseText;
            len = responseText.length;
            for (i = 0; i < len; i++) {



                byteArray.push(responseText.charCodeAt(i) & 0xFF);
            }
        }

        return byteArray;
    },


    injectVBScript: function () {
        var scriptTag = document.createElement('script');
        scriptTag.type = 'text/vbscript';
        scriptTag.text = [
            'Function getIEByteArray(byteArray, out)',
                'Dim len, i',
                'len = LenB(byteArray)',
                'For i = 1 to len',
                    'out.push(AscB(MidB(byteArray, i, 1)))',
                'Next',
            'End Function'
        ].join('\n');
        Ext.getHead().dom.appendChild(scriptTag);
        this.self.vbScriptInjected = true;
    },


    nativeBinaryPostSupport: function () {
        return Ext.isChrome ||
            (Ext.isSafari && Ext.isDefined(window.Uint8Array)) ||
            (Ext.isGecko && Ext.isDefined(window.Uint8Array));
    }


});

